class OrderItem < ActiveRecord::Base
  
  include DynamicDefaultScoping
  
  validates :order_id,    
    :presence => true
  validates :enterprise_id, :presence => true
  validates :ordered_count,
    :numericality => {
      :greater_than_or_equal_to => 1
    }

  belongs_to :order
  belongs_to :updated_by_user, :class_name => 'User', :foreign_key => :updated_by_user_id
  belongs_to :feed
  has_many :feeds, :dependent => :destroy, :order => 'position asc'

  default_scope :current_enterprise,lambda {where(:enterprise_id => Enterprise.current_id )}
  scope :completed,lambda{ where('feeds.type = ? ', 'Feed::OrderItemCompleted').includes(:feed)}
  scope :uncompleted,lambda{ where('feeds.type != ? ', 'Feed::OrderItemCompleted').includes(:feed)}

  def self.order_ids_by_feed_type(feed_type)
    logger.debug "========================================="
    logger.debug "=== 1. OrderItem.order_ids_by_feed_type('#{feed_type}')"
    logger.debug "========================================="
    OrderItem.select('order_id').where('feeds.type = ? ', feed_type).includes(:feed).each_with_object([]) do |order_item,order_ids|
      order_ids << order_item.order_id
    end.uniq
  end

  def reset_after_serviced_cost!
    update_attributes! :after_serviced_cost => AfterService.where(:order_item_id => id).sum(:after_serviced_cost)
    order.reset_after_serviced_cost!
  end
  
  after_create do |order_item|
    Feed::OrderItemCreated.create!(:order_item_id => order_item.id)
  end

  before_save do |order_item|
    order_item.updated_by_user_id = User.current_id if order_item.changed?
  end

  def reset_feed!
    update_attributes :feed_id => Feed.where(:order_item_id => id).last.try(:id)
    order.reset_feeded_at!
  end
  
  # 允许入库登记？
  def allowed_to_be_entered?
    OrderMade.where(:order_item_id => id).any?
  end

  # 允许向厂家支付？
  def allowed_to_be_payed?
    OrderMade.where(:order_item_id => id).has_been_sent_to_factory.any?
  end
  
  # 允许派工安装的完成或未完成？
  def allowed_to_be_installed?    
    Installation.where(:order_item_id => id).has_been_sent_to_installer.any?
  end

  # 允许售后服务的完成或未完成？
  def allowed_to_be_after_serviced?
    AfterService.where(:order_item_id => id).has_been_sent_to_after_service.any?
  end

  def allowed_to_be_over?
    feeds.each do |feed|
      return false if feed.is_a?(Feed::OrderItemCompleted)
    end
    return true
  end

  # 已安装总数
  def installed_count
    Installation.where(:order_item_id => id).sum(:installed_count).to_i
  end

  def how_much
    OrderMadePayment.where(:order_item_id => id).sum(:how_much)
  end

  def gathered_balance
    Installation.where(:order_item_id => id).sum(:gathered_balance) + AfterService.where(:order_item_id => id).sum(:gathered_balance)
  end

  # 派工中数(派工中的数量）
  def has_been_sent_to_installer_count
    Installation.where(:order_item_id => id).has_been_sent_to_installer.sum(:has_been_sent_to_installer_count).to_i
  end

  # 订做中数
  def being_order_made_count
    OrderMade.where(:order_item_id => id).has_been_sent_to_factory.sum(:order_made_count).to_i
  end

  # 已入库
  def entered_count
    Enter.where(:order_item_id => id).sum(:entered_count).to_i
  end
 
  # 预订项结束
  def completed!
    update_attributes :complete_remark => complete_remark,
                        :feed => Feed::OrderItemCompleted.create!(
                        :order_item_id => id)
  end

  # 清空结束备注
  def clear_completed!
    update_attributes :complete_remark => ''
  end
  
  def index
    order.order_items.index(self)
  end
  
end
